/**
 * Created by Administrator on 2015/12/17.
 */
"use strict";
var _ = require('underscore');
var imgRule = require('../../../common/imgRule.js');
var F = require('../../../common/function');
var C = require('../../../config/index');
var _o2oServiceApi = require('../../../common/o2oServiceApi');
var o2oServiceApi = new _o2oServiceApi;

exports.getUpYunImage = function (ware) {
  let images_array = [];
  if(ware.images && ware.images.length>0){
    for (let image of ware.images) {
      images_array.push(imgRule.str2imgURI(image)[0].imgURI + C.upyun.suffix);
    }
  }
  ware.images = images_array;
};

exports.validateFields = function (obj,key_validate_array){
  let error_msg = '';
  for (let p of key_validate_array) {
    if (typeof ( obj [p]) != " function ") {
      if (obj[p] == undefined || _.isEmpty(_.str.trim(obj[p]))) {
        error_msg += p + ' is undefined or empty,';
      } else if (_.v.isIn(p, ['offLineTtime','onLineTime'])) {
        if (!_.v.isDate(obj[p])) {
          error_msg += p + ' is not a valid date,';
        }
      } else if (_.v.isIn(p, ['price','marketPrice'])) {
        if (!_.v.isFloat(obj[p])) {
          error_msg += p + ' is not a valid float number,';
        }
      } else if (_.v.isIn(p, ['categories', 'shops', 'images','services'])) {
        if (!_.isArray(obj[p])) {
          error_msg += p + ' is not a valid array,';
        }
      } else if (_.v.isIn(p, ['totalQuantity','vendorid'])) {
        if (!_.v.isInt(obj[p])) {
          error_msg += p + ' is not valid integer,';
        }
      }
    }
  }
  if (error_msg != '') {
    error_msg += 'please check.';
  }
  return error_msg;
};

exports.generate_img_signature = function *(ware) {
  let ware_images_array=[];
  ware.imgArr = [];
  if (ware.images && !_.isEmpty(ware.images)) {
    for (let img of ware.images) {
      ware.imgArr.push({key: 'image'});
    }
  }
  let signArr = [];
  let imgArray = [];
  for (let i = 0; i < ware.imgArr.length; i++) {
    let imgStr = imgRule.id2imgStr('W', ware.id, 'jpg');//W-1234567-654321.jpg
    imgArray.push({key: ware.imgArr[i].key, imgStr: imgStr});
    signArr[i] = yield F.getUpyunSignB(imgRule.str2imgURI(imgStr)[0]);
    signArr[i].wareid = ware.id;
  }
  let images_array = _.filter(imgArray, function (image) {
    return image.key == 'image';
  });
  let image_string = '';
  for (let image of images_array) {
    ware_images_array.push(image.imgStr);
  }
  if (ware.images && !_.isEmpty(ware.images)) {
    ware.images = ware_images_array;
  }
  ware.upYunSign = signArr;
};
exports.deleteUnuselessFields = function (ware) {
  return _.pick(ware, 'id', 'name', 'categories', 'shops', 'services', 'auditStatus', 'status', 'version','auditLog','images',
    'vendorid', 'graphicDetails', 'offLineTtime', 'onLineTime', 'newest', 'totalQuantity', 'marketPrice','price','upYunSign');
};

//项目上架操作
exports.wareOnSell = function *(id) {
  let wareDetail = yield o2oServiceApi.post('ware', 'detailVersion', 1, {act: 1, id: id});
  if (wareDetail && wareDetail['result']) {
    let vendor_detail = yield o2oServiceApi.post('vendor', 'detail', 1, {act: 1, id: wareDetail['result'].vendorid});
    if (!(vendor_detail && vendor_detail['result'] && vendor_detail['result']['status'] == 1)) {
      return '商品所属的商家无效，不能上架.';
    }
    let shops_array = wareDetail['result']['shops'];
    let exist_valid_shop = false;
    for (let shop of shops_array) {
      let shopId = shop.sid;
      let shopDetail = yield o2oServiceApi.post('shop', 'detail', 1, {act: 1, id: shopId});
      if (shopDetail && shopDetail['result'] && shopDetail['result']['status'] == 1) {
        exist_valid_shop = true;
        break;
      }
    }
    if (!exist_valid_shop) {
      return '没有有效的机构出售该项目，不能上架';
    }
    if (wareDetail['result']['auditStatus'] == 2 && wareDetail['result']['status'] == 1 && wareDetail['result']['newest'] == 1) {
      let wareid = wareDetail['result']['wareid'];
      let ware_onSell_result = yield o2oServiceApi.post('ware', 'synchrodata', 1, {act: 1, wareVersionid: id});
      if (parseInt(ware_onSell_result['result']['error']) == 1 || ware_onSell_result.status == 400) {
        return ware_onSell_result['wareVersionid']['msg'];
      } else {
        let ware_version_update = {id: id, isSell: 1,act:1};
          let ware_version_update_result = yield o2oServiceApi.post('ware', 'updateVersion', 1, ware_version_update);
        if (ware_version_update_result.status == 200) {
          return 'done';
        }

      }
    } else {
      return '输入的项目状态不符，不能进行上架操作.';
    }
  } else {
    return '系统找不到指定的项目.';
  }
};
//项目下架操作
exports.wareSoldOut = function *(id) {
  let wareDetail = yield o2oServiceApi.post('ware', 'detailVersion', 1, {act: 1, id: id});
  if (wareDetail && wareDetail['result']) {
    if (wareDetail['result']['auditStatus'] == 2 && wareDetail['result']['status'] == 1 && wareDetail['result']['newest'] == 1) {
      let wareid = wareDetail['result']['wareid'];
      let ware_version_update = {id: id, isSell: 0,act:1};
      let ware_version_update_result = yield o2oServiceApi.post('ware', 'updateVersion', 1, ware_version_update);
      if (ware_version_update_result.status == 200) {
        let ware_update = yield o2oServiceApi.post('ware', 'update', 1, {id: wareid, act: 1, isSell: 0});
        if (ware_update.status == 200) {
          return 'done';
        }
      }
    } else {
      return '输入的项目状态不符，不能进行下架操作.';
    }
  } else {
    return '系统找不到指定的项目.';
  }
};

exports.warePropertyForList = function (ware) {
  let obj_ware = _.pick(ware, 'id', 'name', 'price', 'totalQuantity', 'buyNumber', 'auditStatus', 'offLineTtime', 'onLineTime');
  if (obj_ware.totalQuantity == undefined || !obj_ware.totalQuantity) {
    obj_ware.totalQuantity = 0;
  }
  if (obj_ware.buyNumber == undefined || !obj_ware.buyNumber) {
    obj_ware.buyNumber = 0;
  }
  obj_ware.remaining = obj_ware.totalQuantity - obj_ware.buyNumber;
  if (obj_ware.offLineTtime == undefined) {
    obj_ware.offLineTtime = 0;
  }
  return obj_ware;
};


exports.generate_organization_list = function *(vendorid,shops){
  let vendorCityData = yield o2oServiceApi.post('shop', 'getDistrict', 1, {act: 1, vendorid: vendorid});
  if (parseInt(vendorCityData['result']['error']) == 1 || vendorCityData.status == 400) {
    return [];
  } else {
    if (vendorCityData['result'].length == 0) {
      return [];
    } else {

    }
  }
};